package com.etc.library.controller;

import com.etc.library.pojo.Book;
import com.etc.library.service.BookService;
import com.etc.library.util.ResultBody;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;


@RestController
@RequestMapping("/book")
public class BookController {

    @Value("${file.real_path}")
    private String realPath;

    @Value("${file.access_path}")
    private String accessPath;

    @Autowired
    private BookService bookService;


    @PostMapping("/upload")
    public ResultBody uploadImg(@RequestParam("cover") MultipartFile multipartFile) {
        //获取上传文件的原始名称
        String oldName = multipartFile.getOriginalFilename();

        String ext = oldName.substring(oldName.lastIndexOf("."));
        String newName = UUID.randomUUID().toString().replace("-", "") + ext;

        File file = new File(realPath, newName);
        try {
            multipartFile.transferTo(file);
            return ResultBody.success(accessPath + newName);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @PostMapping("/add")
    public ResultBody add(@RequestBody Book book) {
        if (bookService.add(book)) {
            return ResultBody.success();
        }
        return ResultBody.error();
    }


    @GetMapping("/list")
    public ResultBody list(@RequestParam Map<String, Object> params) {
        int pageNum = 1;
        int pageSize = 999;
        try {
            pageNum = Integer.parseInt(params.get("pageNum").toString());
            pageSize = Integer.parseInt(params.get("pageSize").toString());
        }catch (Exception e){

        }
        //一定要写在集合获取之前
        PageHelper.startPage(pageNum,pageSize);
        List<Map<String, Object>> list = bookService.list(params);
        PageInfo info = new PageInfo(list);
        return ResultBody.success(info);
    }
}
